//
//  ZYZUserAcount.swift
//  MyWeiBo
//
//  Created by 牛牛很牛 on 15/12/20.
//  Copyright © 2015年 曾勇召. All rights reserved.
//

import UIKit

class ZYZUserAcount: NSObject, NSCoding {
    
    //=类属性，保存用户是否登录
    class var userLogin : Bool {
        return (ZYZUserAcount.loadUserAccount() != nil) ? true : false
    }
    
    //accessToken
    var access_token : String?
    
    //uid
    var uid : String?
    
    //生命周期返回的是一个int类型，不能定义为可选，否则KVC找不到
    var expires_in : NSTimeInterval = 0 {
        didSet{
            //自己来生成过期时间的NSDate
            expires_Date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    //过期时间
    var  expires_Date : NSDate?
    
    //用户昵称
    var screen_name : String?
    
    //头像地址 180*180
    var avatar_large : String?
    
    
    
    //字典转模型
    init(dict :[String : AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    //当字典里的key在模型里面找不到属性时调用，使系统不会报错
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        //什么都不用做
    }
    
    //保存对象内容
    override var description:String {
        get{
            return "accessToken:\(access_token) , uid: \(uid) , expires_in : \(expires_in) , expires_Date : \(expires_Date)"
        }
    }
    
    //加载用户数据
    func  loadUserInfo(finished:(error : NSError?) ->()) {
    //掉用网络工具类
        ZYZNetworkTool.shareNetworkTool1.loadUserInfo { (result, error) -> () in
            //判断是否有错误
            if error != nil && result == nil{
            //有错误
                finished(error: error)
                return
            }
            //没错误，解析服务器返回的数据，获取头像和昵称
           self.screen_name = result!["screen_name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            
            //保存到沙河
            self.saveUserAccount()
            
            //将最新的对象(self)返回
            ZYZUserAcount.userAccount = self
            //h获取用户成功
            finished(error: nil)

            
        }
    }
    
    
    
    //归档与反归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expires_Date, forKey: "expires_Date")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")


    }
    
     required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expires_Date = aDecoder.decodeObjectForKey("expires_Date") as? NSDate
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String

    
    }
    
    //获取沙盒文件名
    
   static let path = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAcount.plist")
    
    
    
    
    //保存信息
    func saveUserAccount(){
        NSKeyedArchiver.archiveRootObject(self, toFile: ZYZUserAcount.path)
    }
    
    //将loadUserAccount对象保存到内存中，而不是每次都去沙盒取，以高效率
    static var userAccount : ZYZUserAcount? ///<本身就含有账户信息
    
    //加载用户信息，类方法,返回账户模型
    class func loadUserAccount()  -> ZYZUserAcount?{
        //先去内存中看
        if userAccount == nil{
               userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? ZYZUserAcount
        }
        if userAccount != nil && userAccount!.expires_Date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
            //说明datem没有过期
            return userAccount
        }else{
            print("账号没加载到")
            return nil
        }
    }
    
    
    
    
    

}



